package com.zlzlib.librx;

import android.content.Context;
import android.text.TextUtils;

import com.zlzlib.librx.listener.ProgressListener;


/**
 * Created by zlz on 2019/8/19.
 */
public abstract class BaseProgressObserver<T> extends BaseObserver<T> implements ProgressListener {

    private BaseProgressDialogHandler mProgressDialogHandler;

    protected abstract BaseProgressDialogHandler dialogHandler(Context context, boolean cancelable);

    public BaseProgressObserver(Context context, boolean cancelable) {
        mProgressDialogHandler = dialogHandler(context, cancelable);
    }

    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        showProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
    }

    /**
     * 完成，隐藏ProgressDialog
     */
    @Override
    public void onComplete() {
        dismissProgressDialog();
    }

    private void showProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.handleMessage(BaseProgressDialogHandler.SHOW_PROGRESS_DIALOG);
        }
    }

    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.handleMessage(BaseProgressDialogHandler.DISMISS_PROGRESS_DIALOG);
            mProgressDialogHandler = null;
        }
    }

    public void messageProgressDialog(String msg) {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.handleMessage(BaseProgressDialogHandler.MESSAGE_PROGRESS_DIALOG, msg);
        }
    }


    @Override
    public void updateDown(ProgressInfo info) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(info.getMsg())) {
            sb.append(info.getMsg()).append("\n");
        }
        sb.append(info.getPercent()).append("%");
        messageProgressDialog(sb.toString());
    }

    @Override
    public void updateUp(ProgressInfo info) {
    }
}
